package pl.edu.agh.neuraleconomy.common.utils;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.log4j.Logger;
import org.joda.time.DateTime;
import org.joda.time.Days;

public class DateUtils {
	
	private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
	private static Logger logger = Logger.getLogger(DateUtils.class);
	
	public static Date trimDate(Date date){
		Calendar c = getCalendar(date);
		c.set(Calendar.HOUR_OF_DAY, 0);
		c.set(Calendar.MINUTE, 0);
		c.set(Calendar.SECOND, 0);
		c.set(Calendar.MILLISECOND, 0);
		return c.getTime();
	}
	
	public static Date addDays(Date date, int daysAmount){
		Calendar c = getCalendar(date);
		c.add(Calendar.DAY_OF_YEAR, daysAmount);
		return c.getTime();
	}
	
	private static Calendar getCalendar(Date date){
		Calendar c = Calendar.getInstance();
		c.setTime(date);
		return c;
	}
	
	public static Date getByString(String dateString){
		try {
			return DATE_FORMAT.parse(dateString);
		} catch (ParseException e) {
			logger.error("Nie udalo sie sparsowac daty: " + dateString, e);
			return null;
		}
	}
	
	public static String formatDate(Date date){
		return DATE_FORMAT.format(date);
	}
	
	public static int getDaysDifferenceBetweenDates(Date from, Date to){
		Days d = Days.daysBetween(new DateTime(from), new DateTime(to));
		return d.getDays();
	}
}
